using CommunityToolkit.Mvvm.ComponentModel;
using System.Diagnostics;
using System.Windows.Controls;
using Microsoft.Extensions.DependencyInjection;
using MiniTheme.Services.Interfaces;

namespace MiniTheme.Services;
//直接操作 ContentControl的方式，而不是通过事件和数据绑定的方式。
public class NavigationService : ObservableObject, INavigationService
{
    private readonly IServiceProvider _serviceProvider;
    //导航载体控件
    private ContentControl? _contentControl;
    //导航到的页面
    private UserControl? _currentPage;
    public UserControl? CurrentPage
    {
        get => _currentPage;
        set => SetProperty(ref _currentPage, value);
    }
    //host中默认就会注入IServicsProvide，这里直接依赖注入
    public NavigationService(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }
    public void SetNavigationControl(ContentControl contentControl)
    {
        Debug.WriteLine($"初始化导航服务，ContentControl: {contentControl != null}");
        _contentControl = contentControl;
    }

    public void NavigateTo<T>() where T : UserControl
    {
        Debug.WriteLine($"准备导航到页面: {typeof(T).Name}, ContentControl可用: {_contentControl != null}");

        if (_contentControl == null)
        {
            Debug.WriteLine("错误: ContentControl为空，无法导航");
            return;
        }
        CurrentPage = _serviceProvider.GetRequiredService<T>();
        Debug.WriteLine($"创建了新页面: {CurrentPage != null}");
        _contentControl.Content = CurrentPage;
        Debug.WriteLine($"设置ContentControl.Content为新页面");
    }

    public void NavigateTo(UserControl page)
    {
        Debug.WriteLine($"直接导航到页面: {page?.GetType().Name}, ContentControl可用: {_contentControl != null}");

        if (_contentControl == null)
        {
            Debug.WriteLine("错误: ContentControl为空，无法导航");
            return;
        }

        CurrentPage = page;
        _contentControl.Content = page;
        Debug.WriteLine($"设置ContentControl.Content为提供的页面");
    }
}
